package gogoqiu.plugin;

import java.io.IOException;

import org.codehaus.groovy.ant.Groovy;
import org.gradle.api.DefaultTask;
import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.plugins.JavaPlugin;
import org.gradle.api.plugins.PluginContainer;
/*
 替代@Plugin
 * gradlePlugin {
    plugins {
        myPlugin { 
            id = 'gogoqiu.plugin.project' // 插件唯一 ID（使用时需引用此 ID）
            implementationClass = 'gogoqiu.plugin.ProjectInfoUpdate' // 插件实现类的全路径
    产生meta-info
 */
//import org.gradle.api.annotations.Plugin;
import org.gradle.api.plugins.PluginManager;
import org.gradle.api.tasks.SourceSetContainer;
import org.gradle.api.tasks.TaskProvider;
//import org.gradle.internal.impldep.org.apache.maven.model.PluginContainer;
import org.gradle.api.logging.Logger;;

/*
 * 如果public class ProjectInfoUpdate implements Plugin<Project> { 
 *  apply的同时输出一个变量：
 *      ext，然后项目的版本引用此变量
 *  如果可能，在编译成功后更新json版本号
 * build.gradle
 *  implementationClass = 'gogoqiu.plugin.ProjectInfoUpdate' // 插件实现类的全路径
 */
public class ProjectInfoUpdate implements Plugin<Project> { 

    /*
     * project.getExtensions().getExtraProperties(), project.getProperties()区别
     * gradle -Penv=prod，通过-p注册全局变量？
     */
    void demo( Project project ){
        project.getExtensions();
        // project.getExtensions().create
        project.getExtensions().getExtraProperties();
        project.getProperties();
        // 获取 sourceSets 配置
        SourceSetContainer sourceSets = project.getExtensions().getByType(SourceSetContainer.class);
        TaskProvider pluginTask = project.getTasks().register("sayhello", DefaultTask.class, task -> {
            task.doLast(t -> System.out.println("插件任务执行！"));
        });
        project.getPlugins().withId("java", javaPlugin -> {
            // @1
            project.getTasks().named("assemble").configure(assembleTask -> {
                assembleTask.dependsOn(pluginTask);
            });
        });
    }

    /*

    Resource missing. [HTTP HEAD: https://repo.maven.apache.org/maven2/gogoqiu/plugin/project/0.0.10/project-0.0.10.pom]
    Resource missing. [HTTP HEAD: https://repo.maven.apache.org/maven2/gogoqiu/plugin/project/0.0.10/project-0.0.10.pom]
    Resource missing. [HTTP HEAD: https://dl.google.com/dl/android/maven2/gogoqiu/plugin/project/0.0.10/project-0.0.10.pom]
    Caching disabled for InstrumentationAnalysisTransform: C:\Users\Administrator\.m2\repository\gogoqiu\plugin\project\0.0.10\project-0.0.10.jar because:
    Build cache is disabled
    Caching not enabled.
    Caching disabled for MergeInstrumentationAnalysisTransform: C:\Users\Administrator\.gradle\caches\9.2.0\transforms\0ea45d73364c0822cf6eb5864202cb7e\workspace\transformed\analysis\instrumentation-dependencies.bin because:
    Build cache is disabled
    Caching not enabled.
    Caching disabled for MergeInstrumentationAnalysisTransform: C:\Users\Administrator\.m2\repository\gogoqiu\plugin\project\0.0.10\project-0.0.10.jar because:
    Build cache is disabled
    Caching not enabled.
    Caching disabled for ExternalDependencyInstrumentingArtifactTransform: C:\Users\Administrator\.gradle\caches\9.2.0\transforms\b9888aa54de32b52a57c9c21dc5b14d0\workspace\transformed\merge\instrumentation-dependencies.bin because:
    Build cache is disabled
    Caching not enabled.
    Caching disabled for ExternalDependencyInstrumentingArtifactTransform: C:\Users\Administrator\.m2\repository\gogoqiu\plugin\project\0.0.10\project-0.0.10.jar because:
    Build cache is disabled
    Caching not enabled.
    当前工作目录: D:\\init\\java\\my-simple-library\\plugin\\usePlugin
    ---UpdateVersion---
    版本更新到:0.0.1=>0.0.2
    project name: usePlugin
    Caching disabled for Groovy DSL script compilation (proj) because:
    Build cache is disabled
    Not worth caching.
    Compiling build file 'D:\\init\\java\\my-simple-library\\plugin\\usePlugin\\build.gradle' using BuildScriptTransformer.
    set project name: demo
    注意：settings.gradle 是项目加载阶段执行的，一旦项目加载完成（进入 build.gradle 的执行阶段），名称就无法再修改了。
    如何在public void apply(Project project) {  注册一个变量var1, 并在build.gradle可以print?
        1. project.getExtensions().getExtraProperties().set("var1", "这是 var1 的值");
        println var1 // 输出：这是 var1 的值
        2. MyExtension extension = project.getExtensions().create("myConfig", MyExtension.class);
        // 设置 var1 的值
        extension.setVar1("这是 var1 的值");
        // 打印扩展中的 var1
        println myConfig.var1 // 输出：这是 var1 的值
    */    
    @Override
    public void apply(Project project) {        
        // 不建议在插件中使用 System.out.println() 输出信息，因为：
        Logger logger = project.getLogger();
        // 输出不同级别的日志
        //logger.debug("这是调试日志，通常用于开发阶段"); // 调试级（默认不显示，需开启 debug 模式）
        //logger.info("插件开始执行..."); // 信息级（常规执行信息）
        //logger.warn("注意：存在未配置的参数"); // 警告级（需要关注的潜在问题）
        //logger.error("执行失败：找不到指定文件"); // 错误级（严重问题，影响执行）

        String currentDir = System.getProperty("user.dir");
        logger.info("当前工作目录: " + currentDir);
        PluginContainer container = project.getPlugins();
        // 或者用字符串 ID（注意：java-library 实际也是 java）
        
        if( container.hasPlugin("java") || container.hasPlugin("java-library")
            || container.hasPlugin("com.android.library") || container.hasPlugin("com.android.application")){
            VersionUpdater updater = new VersionUpdater(logger);
            try {
                updater.updateVersion(project);
            } catch (IOException e) {
                logger.info("IO错误: " + e.getMessage());
                throw new RuntimeException(e.getMessage());
            }
        }else{
            // 会中断编译过程？
            throw new RuntimeException("只能在java/java-library/android/android.library扩展存在时才能使用");
        }        

        if( true )
            return;
        PluginManager manager = project.getPluginManager();
        /*
         * plugins {
            id 'java-library'},  PluginManager manager = project.getPluginManager();manager.hasPlugin("java-library")是真吗
         */
        if( manager.hasPlugin("java") || manager.hasPlugin("java-library")
            || manager.hasPlugin("com.android.library") || manager.hasPlugin("com.android.application")){
            VersionUpdater updater = new VersionUpdater(logger);
            try {
                updater.updateVersion(project);
            } catch (IOException e) {
                logger.info("IO错误: " + e.getMessage());
                throw new RuntimeException(e.getMessage());
            }
        }else{
            // 会中断编译过程？
            throw new RuntimeException("只能在java/java-library/android/android.library扩展存在时才能使用");
        }        
    }    
}
